<template>
    <el-button plain @click="dialogVisible = true" style="margin-bottom: 20px;">
        上传用例
    </el-button>

    <el-dialog v-model="dialogVisible" title="上传API用例" width="500" :before-close="handleClose" destroy-on-close>
        <el-form ref="formRef" style="max-width: 600px" :model="numberValidateForm" label-width="auto"
            class="demo-ruleForm">
            <el-form-item label="用例名称" prop="case_name" :rules="[
                { required: true, message: '用例名称是必填项' },
            ]">
                <el-input v-model="case_name" type="text" autocomplete="off" />
            </el-form-item>

            <el-form-item label="所属模块" prop="functional" :rules="[
                { required: true, message: '所属模块是必填项' },
            ]">
                <el-select v-model="functional" placeholder="请选择所属模块" size="large" style="width: 600px">
                    <el-option v-for="item in functional_options" :key="item.value" :label="item.label"
                        :value="item.value" />
                </el-select>
            </el-form-item>
        </el-form>

        <el-upload ref="uploadRef" class="upload-demo" :auto-upload="false" :before-upload="checkFile"
            :on-change="handleFileChange">
            <template #trigger>
                <el-button type="primary" style="margin-right: 20px;">选择文件</el-button>
            </template>

            <el-button class="ml-3" type="success" @click="submitUpload">
                上传到服务器
            </el-button>

            <template #tip>
                <div class="el-upload__tip">
                    只能上传 .json 或 .yaml 文件，文件大小需小于 500kb
                </div>
            </template>
        </el-upload>
    </el-dialog>

     <el-table :data="tableData" stripe style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }" :cell-style="{ padding: '8px 0' }"
        @row-click="handleRowClick">

        <el-table-column type="selection" width="55" align="center" />

        <el-table-column prop="case_name" label="用例名称" width="180" show-overflow-tooltip>
            <template #default="{ row }">
                <el-tag effect="plain">{{ row.case_name }}</el-tag>
            </template>
        </el-table-column>

        <el-table-column prop="create_time" label="创建时间" width="180" :formatter="formatTime" />

        <el-table-column prop="functional" label="所属模块" width="180" show-overflow-tooltip />

        <el-table-column prop="execute_time" label="执行时间" width="180" :formatter="formatTime" />

        <el-table-column prop="status" label="状态" width="120" align="center">
            <template #default="{ row }">
                <el-tag v-if="row.status === '0'" type="info">
                    未执行
                </el-tag>
                <el-tag v-else-if="row.status === '1'" type="success">
                    已执行
                </el-tag>
                <el-tag v-else type="warning">
                    未知状态
                </el-tag>
            </template>
        </el-table-column>


        <el-table-column label="操作" align="center" fixed="right">
            <template #default="{ row }">
                <el-button type="success" size="small" @click="executeCase(row)" :disabled="isCaseExecuting || row.status === '1'">
                    <el-icon v-if="isExecuting && row.id === currentExecutingCaseId">
                        <Loading />
                    </el-icon>
                    <el-icon v-else>
                        <Play />
                    </el-icon>
                    {{ isExecuting && row.id === currentExecutingCaseId ? '执行中...' : '立即执行' }}
                </el-button>
                <el-button type="primary" size="small" @click="downloadCase(row)">
                    <el-icon>
                        <Download />
                    </el-icon>
                    下载
                </el-button>
                <el-button type="danger" size="small" @click="deleteCase(row)">
                    删除
                </el-button>
            </template>
        </el-table-column>
    </el-table>

    <el-pagination v-model:current-page="currentPage4" v-model:page-size="pageSize4" :page-sizes="[10, 20, 50, 100]"
        :size="size" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
        :total=total @size-change="handleSizeChange" @current-change="handleCurrentChange" />
</template>

<script setup>
import { ref, onMounted, onUnmounted, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import { Download, Document, Loading, Play } from '@element-plus/icons-vue';

const uploadRef = ref(null);
const currentFile = ref(null);
const tableData = ref([]);
const currentPage4 = ref(1);
const pageSize4 = ref(5);
const total = ref('');
const dialogVisible = ref(false);
const isExecuting = ref(false); // 加载状态
const isCaseExecuting = ref(false); // 禁用状态
const currentExecutingCaseId = ref(null); // 当前执行的用例ID

const handleFileChange = (file) => {
    currentFile.value = file.raw;
};

const checkFile = (file) => {
    const isJson = file.type === 'application/json' || file.name.endsWith('.json');
    const isYaml = file.type === 'application/yaml' || file.name.endsWith('.yaml') || file.name.endsWith('.yml');
    
    if (!isJson && !isYaml) {
        ElMessage.error('仅支持.json或.yaml格式');
        return false;
    }
    return true;
};

const case_name = ref('');
const functional = ref('');

const functional_options = [
    { value: '0', label: '用户模块' },
    { value: '1', label: '订单模块' },
    { value: '2', label: '支付模块' }
];

const numberValidateForm = reactive({
    case_name: case_name,
    functional: functional
});

const formatTime = (row, column, cellValue) => {
    if (!cellValue) return '-';
    return new Date(cellValue).toLocaleString();
};

const submitUpload = async () => {
    if (!currentFile.value) return ElMessage.warning('请选择文件');
    if (!case_name.value) return ElMessage.warning('请输入用例名称');
    if (!functional.value) return ElMessage.warning('请选择所属模块');

    const formData = new FormData();
    formData.append('file', currentFile.value);
    formData.append('case_name', case_name.value);
    formData.append('functional', functional.value);
    
    dialogVisible.value = false;
    
    try {
        const response = await axios.post('http://127.0.0.1:8000/apiautomation/upload', formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        });
        
        if (response.data.status === 200) {
            ElMessage.success(response.data.message);
            getdata();
        } else {
            ElMessage.error(response.data.message || '上传失败');
        }
    } catch (err) {
        console.error('上传错误:', err);
        ElMessage.error('上传失败，请重试');
    }
};

function executeCase(row) {
    isExecuting.value = true;
    isCaseExecuting.value = true;
    currentExecutingCaseId.value = row.id;
    
    axios.post(`http://127.0.0.1:8000/apiautomation/execute/${row.id}`)
    .then(res => {
        if (res.data.status === 200) {
            ElMessage.success('用例执行成功，报告已生成');
            getdata();
        } else {
            ElMessage.error(res.data.message || '用例执行失败');
        }
        isExecuting.value = false;
        isCaseExecuting.value = false;
        currentExecutingCaseId.value = null;
    })
    .catch(err => {
        console.error('执行错误:', err);
        ElMessage.error('执行失败，请重试');
        isExecuting.value = false;
        isCaseExecuting.value = false;
        currentExecutingCaseId.value = null;
    });
}

function downloadCase(row) {
    axios.get(`http://127.0.0.1:8000/apiautomation/download/${row.id}`, {
        responseType: 'blob'
    })
    .then(response => {
        const contentDisposition = response.headers['content-disposition'];
        let fileName = `${row.case_name}`;
        
        // 从路径获取文件扩展名
        const casePath = row.case_path;
        const ext = casePath.substring(casePath.lastIndexOf('.'));
        fileName += ext;
        
        // 创建下载链接
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', fileName);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        ElMessage.success('下载成功');
    })
    .catch(error => {
        console.error('下载失败', error);
        ElMessage.error('下载失败，请重试');
    });
}

function deleteCase(row) {
    ElMessageBox.confirm(
        '确定要删除此测试用例吗？关联的报告也将被删除',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    )
    .then(() => {
        axios.delete(`http://127.0.0.1:8000/apiautomation/delete/${row.id}`)
        .then(res => {
            if (res.data.status === 200) {
                ElMessage.success('删除成功');
                getdata();
            } else {
                ElMessage.error(res.data.message || '删除失败');
            }
        })
        .catch(err => {
            console.error(err);
        });
    })
    .catch(() => {
        // 用户取消操作
    });
}

function getdata() {
    axios.get("http://127.0.0.1:8000/apiautomation/apiList", {
        params: {
            page: currentPage4.value,
            pagesize: pageSize4.value
        }
    })
    .then(res => {
        if (res.data.status === 200) {
            tableData.value = res.data.data || [];
            total.value = res.data.total || 0;
        } else {
            ElMessage.error(res.data.message || '获取数据失败');
        }
    })
    .catch(err => {
        console.error(err);
    });
}


// ... (保持其他函数不变) ...

onMounted(() => {
    getdata();
});
</script>

<style scoped>
/* 保持原有样式不变 */
</style>